home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / string.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  20KB  |  582 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. """A collection of string operations (most are no longer used).
  5.  
  6. Warning: most of the code you see here isn't normally used nowadays.
  7. Beginning with Python 1.6, many of these functions are implemented as
  8. methods on the standard string object. They used to be implemented by
  9. a built-in module called strop, but strop is now obsolete itself.
  10.  
  11. Public module variables:
  12.  
  13. whitespace -- a string containing all characters considered whitespace
  14. lowercase -- a string containing all characters considered lowercase letters
  15. uppercase -- a string containing all characters considered uppercase letters
  16. letters -- a string containing all characters considered letters
  17. digits -- a string containing all characters considered decimal digits
  18. hexdigits -- a string containing all characters considered hexadecimal digits
  19. octdigits -- a string containing all characters considered octal digits
  20. punctuation -- a string containing all characters considered punctuation
  21. printable -- a string containing all characters considered printable
  22.  
  23. """
  24. whitespace = ' \t\n\r\x0b\x0c'
  25. lowercase = 'abcdefghijklmnopqrstuvwxyz'
  26. uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  27. letters = lowercase + uppercase
  28. ascii_lowercase = lowercase
  29. ascii_uppercase = uppercase
  30. ascii_letters = ascii_lowercase + ascii_uppercase
  31. digits = '0123456789'
  32. hexdigits = digits + 'abcdef' + 'ABCDEF'
  33. octdigits = '01234567'
  34. punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
  35. printable = digits + letters + punctuation + whitespace
  36. l = map(chr, xrange(256))
  37. _idmap = str('').join(l)
  38. del l
  39.  
  40. def capwords(s, sep = None):
  41.     '''capwords(s [,sep]) -> string
  42.  
  43.     Split the argument into words using split, capitalize each
  44.     word using capitalize, and join the capitalized words using
  45.     join.  If the optional second argument sep is absent or None,
  46.     runs of whitespace characters are replaced by a single space
  47.     and leading and trailing whitespace are removed, otherwise
  48.     sep is used to split and join the words.
  49.  
  50.     '''
  51.     if not sep:
  52.         pass
  53.     return ' '.join((lambda .0: for x in .0:
  54. x.capitalize())(s.split(sep)))
  55.  
  56. _idmapL = None
  57.  
  58. def maketrans(fromstr, tostr):
  59.     '''maketrans(frm, to) -> string
  60.  
  61.     Return a translation table (a string of 256 bytes long)
  62.     suitable for use in string.translate.  The strings frm and to
  63.     must be of the same length.
  64.  
  65.     '''
  66.     global _idmapL
  67.     if len(fromstr) != len(tostr):
  68.         raise ValueError, 'maketrans arguments must have same length'
  69.     len(fromstr) != len(tostr)
  70.     if not _idmapL:
  71.         _idmapL = list(_idmap)
  72.     
  73.     L = _idmapL[:]
  74.     fromstr = map(ord, fromstr)
  75.     for i in range(len(fromstr)):
  76.         L[fromstr[i]] = tostr[i]
  77.     
  78.     return ''.join(L)
  79.  
  80. import re as _re
  81.  
  82. class _multimap:
  83.     '''Helper class for combining multiple mappings.
  84.  
  85.     Used by .{safe_,}substitute() to combine the mapping and keyword
  86.     arguments.
  87.     '''
  88.     
  89.     def __init__(self, primary, secondary):
  90.         self._primary = primary
  91.         self._secondary = secondary
  92.  
  93.     
  94.     def __getitem__(self, key):
  95.         
  96.         try:
  97.             return self._primary[key]
  98.         except KeyError:
  99.             return self._secondary[key]
  100.  
  101.  
  102.  
  103.  
  104. class _TemplateMetaclass(type):
  105.     pattern = '\n    %(delim)s(?:\n      (?P<escaped>%(delim)s) |   # Escape sequence of two delimiters\n      (?P<named>%(id)s)      |   # delimiter and a Python identifier\n      {(?P<braced>%(id)s)}   |   # delimiter and a braced identifier\n      (?P<invalid>)              # Other ill-formed delimiter exprs\n    )\n    '
  106.     
  107.     def __init__(cls, name, bases, dct):
  108.         super(_TemplateMetaclass, cls).__init__(name, bases, dct)
  109.         if 'pattern' in dct:
  110.             pattern = cls.pattern
  111.         else:
  112.             pattern = _TemplateMetaclass.pattern % {
  113.                 'delim': _re.escape(cls.delimiter),
  114.                 'id': cls.idpattern }
  115.         cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)
  116.  
  117.  
  118.  
  119. class Template:
  120.     '''A string class for supporting $-substitutions.'''
  121.     __metaclass__ = _TemplateMetaclass
  122.     delimiter = '$'
  123.     idpattern = '[_a-z][_a-z0-9]*'
  124.     
  125.     def __init__(self, template):
  126.         self.template = template
  127.  
  128.     
  129.     def _invalid(self, mo):
  130.         i = mo.start('invalid')
  131.         lines = self.template[:i].splitlines(True)
  132.         if not lines:
  133.             colno = 1
  134.             lineno = 1
  135.         else:
  136.             colno = i - len(''.join(lines[:-1]))
  137.             lineno = len(lines)
  138.         raise ValueError('Invalid placeholder in string: line %d, col %d' % (lineno, colno))
  139.  
  140.     
  141.     def substitute(self, *args, **kws):
  142.         if len(args) > 1:
  143.             raise TypeError('Too many positional arguments')
  144.         len(args) > 1
  145.         if not args:
  146.             mapping = kws
  147.         elif kws:
  148.             mapping = _multimap(kws, args[0])
  149.         else:
  150.             mapping = args[0]
  151.         
  152.         def convert(mo):
  153.             if not mo.group('named'):
  154.                 pass
  155.             named = mo.group('braced')
  156.             if named is not None:
  157.                 val = mapping[named]
  158.                 return '%s' % (val,)
  159.             if mo.group('escaped') is not None:
  160.                 return self.delimiter
  161.             raise ValueError('Unrecognized named group in pattern', self.pattern)
  162.  
  163.         return self.pattern.sub(convert, self.template)
  164.  
  165.     
  166.     def safe_substitute(self, *args, **kws):
  167.         if len(args) > 1:
  168.             raise TypeError('Too many positional arguments')
  169.         len(args) > 1
  170.         if not args:
  171.             mapping = kws
  172.         elif kws:
  173.             mapping = _multimap(kws, args[0])
  174.         else:
  175.             mapping = args[0]
  176.         
  177.         def convert(mo):
  178.             named = mo.group('named')
  179.             if named is not None:
  180.                 
  181.                 try:
  182.                     return '%s' % (mapping[named],)
  183.                 except KeyError:
  184.                     return self.delimiter + named
  185.                 
  186.  
  187.             None<EXCEPTION MATCH>KeyError
  188.             braced = mo.group('braced')
  189.             if braced is not None:
  190.                 
  191.                 try:
  192.                     return '%s' % (mapping[braced],)
  193.                 except KeyError:
  194.                     return self.delimiter + '{' + braced + '}'
  195.                 
  196.  
  197.             None<EXCEPTION MATCH>KeyError
  198.             if mo.group('escaped') is not None:
  199.                 return self.delimiter
  200.             if mo.group('invalid') is not None:
  201.                 return self.delimiter
  202.             raise ValueError('Unrecognized named group in pattern', self.pattern)
  203.  
  204.         return self.pattern.sub(convert, self.template)
  205.  
  206.  
  207. index_error = ValueError
  208. atoi_error = ValueError
  209. atof_error = ValueError
  210. atol_error = ValueError
  211.  
  212. def lower(s):
  213.     '''lower(s) -> string
  214.  
  215.     Return a copy of the string s converted to lowercase.
  216.  
  217.     '''
  218.     return s.lower()
  219.  
  220.  
  221. def upper(s):
  222.     '''upper(s) -> string
  223.  
  224.     Return a copy of the string s converted to uppercase.
  225.  
  226.     '''
  227.     return s.upper()
  228.  
  229.  
  230. def swapcase(s):
  231.     '''swapcase(s) -> string
  232.  
  233.     Return a copy of the string s with upper case characters
  234.     converted to lowercase and vice versa.
  235.  
  236.     '''
  237.     return s.swapcase()
  238.  
  239.  
  240. def strip(s, chars = None):
  241.     '''strip(s [,chars]) -> string
  242.  
  243.     Return a copy of the string s with leading and trailing
  244.     whitespace removed.
  245.     If chars is given and not None, remove characters in chars instead.
  246.     If chars is unicode, S will be converted to unicode before stripping.
  247.  
  248.     '''
  249.     return s.strip(chars)
  250.  
  251.  
  252. def lstrip(s, chars = None):
  253.     '''lstrip(s [,chars]) -> string
  254.  
  255.     Return a copy of the string s with leading whitespace removed.
  256.     If chars is given and not None, remove characters in chars instead.
  257.  
  258.     '''
  259.     return s.lstrip(chars)
  260.  
  261.  
  262. def rstrip(s, chars = None):
  263.     '''rstrip(s [,chars]) -> string
  264.  
  265.     Return a copy of the string s with trailing whitespace removed.
  266.     If chars is given and not None, remove characters in chars instead.
  267.  
  268.     '''
  269.     return s.rstrip(chars)
  270.  
  271.  
  272. def split(s, sep = None, maxsplit = -1):
  273.     '''split(s [,sep [,maxsplit]]) -> list of strings
  274.  
  275.     Return a list of the words in the string s, using sep as the
  276.     delimiter string.  If maxsplit is given, splits at no more than
  277.     maxsplit places (resulting in at most maxsplit+1 words).  If sep
  278.     is not specified or is None, any whitespace string is a separator.
  279.  
  280.     (split and splitfields are synonymous)
  281.  
  282.     '''
  283.     return s.split(sep, maxsplit)
  284.  
  285. splitfields = split
  286.  
  287. def rsplit(s, sep = None, maxsplit = -1):
  288.     '''rsplit(s [,sep [,maxsplit]]) -> list of strings
  289.  
  290.     Return a list of the words in the string s, using sep as the
  291.     delimiter string, starting at the end of the string and working
  292.     to the front.  If maxsplit is given, at most maxsplit splits are
  293.     done. If sep is not specified or is None, any whitespace string
  294.     is a separator.
  295.     '''
  296.     return s.rsplit(sep, maxsplit)
  297.  
  298.  
  299. def join(words, sep = ' '):
  300.     '''join(list [,sep]) -> string
  301.  
  302.     Return a string composed of the words in list, with
  303.     intervening occurrences of sep.  The default separator is a
  304.     single space.
  305.  
  306.     (joinfields and join are synonymous)
  307.  
  308.     '''
  309.     return sep.join(words)
  310.  
  311. joinfields = join
  312.  
  313. def index(s, *args):
  314.     '''index(s, sub [,start [,end]]) -> int
  315.  
  316.     Like find but raises ValueError when the substring is not found.
  317.  
  318.     '''
  319.     return s.index(*args)
  320.  
  321.  
  322. def rindex(s, *args):
  323.     '''rindex(s, sub [,start [,end]]) -> int
  324.  
  325.     Like rfind but raises ValueError when the substring is not found.
  326.  
  327.     '''
  328.     return s.rindex(*args)
  329.  
  330.  
  331. def count(s, *args):
  332.     '''count(s, sub[, start[,end]]) -> int
  333.  
  334.     Return the number of occurrences of substring sub in string
  335.     s[start:end].  Optional arguments start and end are
  336.     interpreted as in slice notation.
  337.  
  338.     '''
  339.     return s.count(*args)
  340.  
  341.  
  342. def find(s, *args):
  343.     '''find(s, sub [,start [,end]]) -> in
  344.  
  345.     Return the lowest index in s where substring sub is found,
  346.     such that sub is contained within s[start,end].  Optional
  347.     arguments start and end are interpreted as in slice notation.
  348.  
  349.     Return -1 on failure.
  350.  
  351.     '''
  352.     return s.find(*args)
  353.  
  354.  
  355. def rfind(s, *args):
  356.     '''rfind(s, sub [,start [,end]]) -> int
  357.  
  358.     Return the highest index in s where substring sub is found,
  359.     such that sub is contained within s[start,end].  Optional
  360.     arguments start and end are interpreted as in slice notation.
  361.  
  362.     Return -1 on failure.
  363.  
  364.     '''
  365.     return s.rfind(*args)
  366.  
  367. _float = float
  368. _int = int
  369. _long = long
  370.  
  371. def atof(s):
  372.     '''atof(s) -> float
  373.  
  374.     Return the floating point number represented by the string s.
  375.  
  376.     '''
  377.     return _float(s)
  378.  
  379.  
  380. def atoi(s, base = 10):
  381.     '''atoi(s [,base]) -> int
  382.  
  383.     Return the integer represented by the string s in the given
  384.     base, which defaults to 10.  The string s must consist of one
  385.     or more digits, possibly preceded by a sign.  If base is 0, it
  386.     is chosen from the leading characters of s, 0 for octal, 0x or
  387.     0X for hexadecimal.  If base is 16, a preceding 0x or 0X is
  388.     accepted.
  389.  
  390.     '''
  391.     return _int(s, base)
  392.  
  393.  
  394. def atol(s, base = 10):
  395.     '''atol(s [,base]) -> long
  396.  
  397.     Return the long integer represented by the string s in the
  398.     given base, which defaults to 10.  The string s must consist
  399.     of one or more digits, possibly preceded by a sign.  If base
  400.     is 0, it is chosen from the leading characters of s, 0 for
  401.     octal, 0x or 0X for hexadecimal.  If base is 16, a preceding
  402.     0x or 0X is accepted.  A trailing L or l is not accepted,
  403.     unless base is 0.
  404.  
  405.     '''
  406.     return _long(s, base)
  407.  
  408.  
  409. def ljust(s, width, *args):
  410.     '''ljust(s, width[, fillchar]) -> string
  411.  
  412.     Return a left-justified version of s, in a field of the
  413.     specified width, padded with spaces as needed.  The string is
  414.     never truncated.  If specified the fillchar is used instead of spaces.
  415.  
  416.     '''
  417.     return s.ljust(width, *args)
  418.  
  419.  
  420. def rjust(s, width, *args):
  421.     '''rjust(s, width[, fillchar]) -> string
  422.  
  423.     Return a right-justified version of s, in a field of the
  424.     specified width, padded with spaces as needed.  The string is
  425.     never truncated.  If specified the fillchar is used instead of spaces.
  426.  
  427.     '''
  428.     return s.rjust(width, *args)
  429.  
  430.  
  431. def center(s, width, *args):
  432.     '''center(s, width[, fillchar]) -> string
  433.  
  434.     Return a center version of s, in a field of the specified
  435.     width. padded with spaces as needed.  The string is never
  436.     truncated.  If specified the fillchar is used instead of spaces.
  437.  
  438.     '''
  439.     return s.center(width, *args)
  440.  
  441.  
  442. def zfill(x, width):
  443.     '''zfill(x, width) -> string
  444.  
  445.     Pad a numeric string x with zeros on the left, to fill a field
  446.     of the specified width.  The string x is never truncated.
  447.  
  448.     '''
  449.     if not isinstance(x, basestring):
  450.         x = repr(x)
  451.     
  452.     return x.zfill(width)
  453.  
  454.  
  455. def expandtabs(s, tabsize = 8):
  456.     '''expandtabs(s [,tabsize]) -> string
  457.  
  458.     Return a copy of the string s with all tab characters replaced
  459.     by the appropriate number of spaces, depending on the current
  460.     column, and the tabsize (default 8).
  461.  
  462.     '''
  463.     return s.expandtabs(tabsize)
  464.  
  465.  
  466. def translate(s, table, deletions = ''):
  467.     '''translate(s,table [,deletions]) -> string
  468.  
  469.     Return a copy of the string s, where all characters occurring
  470.     in the optional argument deletions are removed, and the
  471.     remaining characters have been mapped through the given
  472.     translation table, which must be a string of length 256.  The
  473.     deletions argument is not allowed for Unicode strings.
  474.  
  475.     '''
  476.     if deletions or table is None:
  477.         return s.translate(table, deletions)
  478.     return s.translate(table + s[:0])
  479.  
  480.  
  481. def capitalize(s):
  482.     '''capitalize(s) -> string
  483.  
  484.     Return a copy of the string s with only its first character
  485.     capitalized.
  486.  
  487.     '''
  488.     return s.capitalize()
  489.  
  490.  
  491. def replace(s, old, new, maxsplit = -1):
  492.     '''replace (str, old, new[, maxsplit]) -> string
  493.  
  494.     Return a copy of string str with all occurrences of substring
  495.     old replaced by new. If the optional argument maxsplit is
  496.     given, only the first maxsplit occurrences are replaced.
  497.  
  498.     '''
  499.     return s.replace(old, new, maxsplit)
  500.  
  501.  
  502. try:
  503.     from strop import maketrans, lowercase, uppercase, whitespace
  504.     letters = lowercase + uppercase
  505. except ImportError:
  506.     pass
  507.  
  508.  
  509. class Formatter(object):
  510.     
  511.     def format(self, format_string, *args, **kwargs):
  512.         return self.vformat(format_string, args, kwargs)
  513.  
  514.     
  515.     def vformat(self, format_string, args, kwargs):
  516.         used_args = set()
  517.         result = self._vformat(format_string, args, kwargs, used_args, 2)
  518.         self.check_unused_args(used_args, args, kwargs)
  519.         return result
  520.  
  521.     
  522.     def _vformat(self, format_string, args, kwargs, used_args, recursion_depth):
  523.         if recursion_depth < 0:
  524.             raise ValueError('Max string recursion exceeded')
  525.         recursion_depth < 0
  526.         result = []
  527.         for literal_text, field_name, format_spec, conversion in self.parse(format_string):
  528.             if literal_text:
  529.                 result.append(literal_text)
  530.             
  531.             if field_name is not None:
  532.                 (obj, arg_used) = self.get_field(field_name, args, kwargs)
  533.                 used_args.add(arg_used)
  534.                 obj = self.convert_field(obj, conversion)
  535.                 format_spec = self._vformat(format_spec, args, kwargs, used_args, recursion_depth - 1)
  536.                 result.append(self.format_field(obj, format_spec))
  537.                 continue
  538.         
  539.         return ''.join(result)
  540.  
  541.     
  542.     def get_value(self, key, args, kwargs):
  543.         if isinstance(key, (int, long)):
  544.             return args[key]
  545.         return kwargs[key]
  546.  
  547.     
  548.     def check_unused_args(self, used_args, args, kwargs):
  549.         pass
  550.  
  551.     
  552.     def format_field(self, value, format_spec):
  553.         return format(value, format_spec)
  554.  
  555.     
  556.     def convert_field(self, value, conversion):
  557.         if conversion == 'r':
  558.             return repr(value)
  559.         if conversion == 's':
  560.             return str(value)
  561.         if conversion is None:
  562.             return value
  563.         raise ValueError('Unknown converion specifier {0!s}'.format(conversion))
  564.  
  565.     
  566.     def parse(self, format_string):
  567.         return format_string._formatter_parser()
  568.  
  569.     
  570.     def get_field(self, field_name, args, kwargs):
  571.         (first, rest) = field_name._formatter_field_name_split()
  572.         obj = self.get_value(first, args, kwargs)
  573.         for is_attr, i in rest:
  574.             if is_attr:
  575.                 obj = getattr(obj, i)
  576.                 continue
  577.             obj = obj[i]
  578.         
  579.         return (obj, first)
  580.  
  581.  
  582.